package com.jy.rhin.support.interceptor;

import com.jy.rhin.support.aspect.AuditAspect;
import com.jy.rhin.support.aspect.AuditLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.ext.logging.event.EventType;
import org.apache.cxf.ext.logging.event.LogEvent;
import org.apache.cxf.ext.logging.slf4j.Slf4jVerboseEventSender;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Description: 重写webService接口日志打印拦截器用到的Sender，在获取日志后，将原始xml串存入上下文，后续打包审计记录需要用到
 * @Author: lww
 * @Date: 2022/5/20
 */
@Slf4j
@Component
public class AuditInfoEventSender extends Slf4jVerboseEventSender {

    @Resource
    ApplicationEventPublisher eventPublisher;

    @Override
    protected String getLogMessage(LogEvent event) {
        String logMessage = event.getPayload();
        EventType type = event.getType();
        //收到请求
        receiveReq(logMessage, type);
        //返回响应
        returnResp(logMessage, type);
        return super.getLogMessage(event);
    }

    /**
     * 收到请求，将入参原始xml存入上下文
     * 后续将进入自定义注解的前置切面{@link AuditAspect#auditBefore(ProceedingJoinPoint, AuditLog)}，获取到接口入参后存入上下文，并触发保存审计信息事件
     *
     * @param logMessage
     * @param type
     */
    private void receiveReq(String logMessage, EventType type) {
        if (type == EventType.REQ_IN) {
            WsXmlThreadLocal.setXml(logMessage);
        }
    }

    /**
     * 返回响应，将出参原始xml存入上下文
     * 并触发保存审计记录的事件，保存审计记录
     * 在此之前，已经在自定义注解后置切面{@link AuditAspect#auditAfter(JoinPoint, AuditLog, Object)}将出参存入上线文
     *
     * @param logMessage
     * @param type
     */
    private void returnResp(String logMessage, EventType type) {
        //总入口进入无需处理
        if (type == EventType.RESP_OUT && !logMessage.contains("HIPMessageServer")) {
            WsXmlThreadLocal.setXml(logMessage);
            eventPublisher.publishEvent(new SaveAuditInfoEvent(EventType.RESP_OUT));
        }
    }

}
